package com.cwj;

import com.cwj.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @author chenwujie
 * @date 2020/11/0211:10
 */
public class ZipTest {
    public static void main(String[] args) throws IOException {
//        long t1 = System.currentTimeMillis();
//        ZipInputStream zipInputStream = new ZipInputStream( new FileInputStream("D:\\task\\task_2.zip"), StandardCharsets.ISO_8859_1);
//        ZipEntry zip = null;
//        while ((zip = zipInputStream.getNextEntry()) != null){
//            if(zip.isDirectory()){
//                continue;
//            }
//            checkFileType(zip.getName());
////            System.out.println(zip.getName());
////            System.out.println(new String(zip.getName().getBytes(StandardCharsets.ISO_8859_1), Charset.forName("GBK")));
//        }
//        long t2 = System.currentTimeMillis();
//
//        System.out.println(t2 -t1);
        File file = new File("D:\\task\\task_4.zip");
        String fileN = file.getName();
        String fileExtensionName = FileUtils.getFileExtensionName(fileN);
        if (!"zip".equals(fileExtensionName)) {
            checkFileType(fileN);
        } else {
            try (InputStream inputStream = new FileInputStream(file)) {
                checkZipEntryType(inputStream);
            }
        }
    }

    private static void checkZipEntryType(InputStream inputStream) throws IOException {
        try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, StandardCharsets.ISO_8859_1)) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                if (zipEntry.isDirectory()) {
                    throw new UnicomException("压缩文件内容不支持文件夹形式。");
                }
                String fileName = zipEntry.getName();
                checkFileType(fileName);
            }
        }
    }
    private static void checkFileType(String fileName) {
        String fileExtensionName = FileUtils.getFileExtensionName(fileName);
        if("zip".equals(fileExtensionName)){
            throw new UnicomException("压缩包内不能有压缩文件，请重新上传!");
        }
        if (!"stp/catproduct/catpart/sat/wrl/igs/3dxml/step/cgr/jpg/jpeg/png/tif/tiff/pdf/docx/doc/dwg/xls/xlsx".contains(fileExtensionName.toLowerCase())) {
            throw new UnicomException("文件格式不符合要求，请重新上传。");
        }
    }
}
